package top.readhub.wopei.client.loader;


import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.readhub.wopei.common.constants.Constants;
import top.readhub.wopei.common.exception.ExceptionCode;
import top.readhub.wopei.common.exception.WoPeiException;

import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * Created by daervin on 2021/6/9
 */
public class LocalLoader implements ILoader {
    private Logger logger = LoggerFactory.getLogger(LocalLoader.class);

    private ZKLoader zkLoader;

    public LocalLoader(ZKLoader zkLoader) {
        this.zkLoader = zkLoader;
    }

    private ConcurrentHashMap<String, String> CACHE = new ConcurrentHashMap<>();

/*    private Cache<String, String> cache = CacheBuilder.newBuilder()
            .concurrencyLevel(5).initialCapacity(10000).maximumSize(100000).expireAfterWrite(365, TimeUnit.DAYS)
            //设置缓存的移除通知
            .removalListener(notification -> {
                System.out.println(notification.getKey() + " " + notification.getValue() + " 被移除,原因:" + notification.getCause());
            }).build();*/

    @Override
    public String getSetting(String code) throws WoPeiException {
        String cacheKey = Constants.CACHE_PREFIX + code;
        try {
            /*return cache.get(cacheKey, new Callable<String>() {
                @Override
                public String call() throws Exception {
                    return zkLoader.getSetting(code);
                }
            });*/
            String val = CACHE.get(cacheKey);
            if (val == null) {
                val = zkLoader.getSetting(code);
                if (val != null) {
                    CACHE.put(cacheKey, val);
                }
            }
            return val;
        } catch (Exception e) {
            throw new WoPeiException(e, ExceptionCode.C_ERROR);
        }
    }

    public void reset(String code, String value) {
        if (StringUtils.isBlank(value)) {
            return;
        }
        String cacheKey = Constants.CACHE_PREFIX + code;
//        cache.put(cacheKey, value);
        CACHE.put(cacheKey, value);
    }

    public void del(String code) {
        String cacheKey = Constants.CACHE_PREFIX + code;
//        cache.invalidate(cacheKey);
        CACHE.remove(cacheKey);
    }
}
